package com.yb.xczx.cloud.auth.filter;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.constant.RedisKeyConstant;
import com.yb.xczx.cache.manager.api.XczxStringCacheManager;
import com.yb.xczx.cloud.auth.bean.XczxSysUser;
import com.yb.xczx.cloud.auth.bean.XczxUserPassAuthenticationToken;
import com.yb.xczx.cloud.auth.bean.vo.XczxSysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/19 13:11
 * FileName: XczxOauth2UserAuthenticationFilter
 * Description:
 */
@Slf4j
public class XczxOauth2UserAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    XczxStringCacheManager xczxStringCacheManager;

    @Autowired
    @Lazy
    JwtDecoder jwtDecoder;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String accessToken = request.getParameter("access_token");

        try {
            String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
            String bearerToken=authorization.substring(7);
            Jwt jwt = jwtDecoder.decode(bearerToken);
            String username = (String) jwt.getClaims().get("sub");
            accessToken = xczxStringCacheManager.getString(String.format(RedisKeyConstant.LOGIN_USER_ACCESS_TOKEN_KEY, username));
            log.info("authorization {}",bearerToken);
        }catch (Exception e){

        }

        if(!StringUtils.hasText(accessToken)){
            filterChain.doFilter(request,response);
            return;
        }

        String result = xczxStringCacheManager.getString(String.format(RedisKeyConstant.LOGIN_USER_DETAIL_KEY, accessToken));

        if(!StringUtils.hasText(result)){
            filterChain.doFilter(request,response);
            return;
        }

        XczxSysUserVo userVo= JSONObject.parseObject(result, XczxSysUserVo.class);
        XczxSysUser xczxSysUser = new XczxSysUser(userVo.getSysUser(), userVo.getAuthorities());

        XczxUserPassAuthenticationToken authenticated = XczxUserPassAuthenticationToken.authenticated(xczxSysUser, xczxSysUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticated);

        filterChain.doFilter(request,response);

    }
}
